function randomString(min, max) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	if(!min) min = 7;
	if(!max) max = 10;
	var string_length = Math.floor(Math.random() * (max - min + 1) + min);

	var randomstring = '';
	for (var i=0; i < string_length ; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

$(document).ready(function(){

    $('input[type=password]').bind('keypress', function(e) {
        if(e.keyCode==13){
            var u = $('#username').val();
		    var p = $('#password').val();
		    $.ajax({
			    type	: 'POST',
			    url		: 'query.php',
			    data	: {login:true, u:u, p:p},
			    dataType: 'html',
			    beforeSend:function(){ $('.loading').html('<img src="css/images/loading.gif" alt="loading" />'); },
			    success	: function(result){
				    if(result == 1){
					    $('.loading').html('');
					    location.reload();
				    }else{
				        alert('คุณกรอกข้อมูลไม่ถูกต้อง หรือไม่มีผู้ใช้นี้.');
				        $('.username').focus();
				        $('.loading').html('');
					    $('#submit').closest('.login-content')
					    .find('input')
					    .css({'border':'1px solid #cd0a0a','background-color':'#e14f1c'});
				    }
			    }
		    });
        }
    });

	// Login
	$('#submit').click(function(){
		var u = $('#username').val();
		var p = $('#password').val();
		$.ajax({
			type	: 'POST',
			url		: 'query.php',
			data	: {login:true, u:u, p:p},
			dataType: 'html',
			beforeSend:function(){ $('.loading').html('<img src="css/images/loading.gif" alt="loading" />'); },
			success	: function(result){
				if(result == 1){
					$('.loading').html('');
					location.reload();
				}else{
					alert('คุณกรอกข้อมูลไม่ถูกต้อง หรือไม่มีผู้ใช้นี้.');
			        $('.username').focus();
			        $('.loading').html('');
				    $('#submit').closest('.login-content')
				    .find('input')
				    .css({'border':'1px solid #cd0a0a','background-color':'#e14f1c'});
				}
			}
		});
		return false;
	});

	// Add more products
	$('a#del_row').click(function(){
		code = $(this).closest('.products-input-template').find('input[type=hidden]').val();
		$(this).closest('.products-input-template').remove();
		$.ajax({
			type	: 'POST',
			url		: 'query.php',
			data	: {del_product:true, code:code},
			dataType: 'html',
			success	: function(msg){

			}
		});
	});
	$('a#add_products').click(function(){
		errors = false;
		name_null = '';
		price_null= '';
		data = {};
		$('.products .products-group').find('.products-input-template').each(function(){

			if($(this).find('input#pname').val()==""){
				name_null = 'รายการสินค้าเป็นค่าว่างไม่ได้';
				errors = true;
			}
			if($(this).find('input#pprice').val()==""){
				price_null = 'ราคาต่อหน่วยสินค้าเป็นค่าว่างไม่ได้';
				errors = true;
			}

		});
		if(errors){
			alert(name_null +'\n'+ price_null);
		}else{
			//$('#add_product_form').serializeArray()[0]['value'];
			even_odd = ($('#add_product_form table tbody tr').attr('class') == "odd")? "even" : "odd";
			unit_id = $('#unit').val();
			unit_name= $('#unit option[value='+unit_id+']').text()

			str='<tr class="'+even_odd+'">';
            str += ' <td align="center">'+(parseInt($('#add_product_form table tbody tr').find('td:eq(0)').first().text())+1)+'</td>';
            str += '<td>'+$('#add_product_form').serializeArray()[0]['value']+'</td>';
            str += '<td>'+$('#add_product_form').serializeArray()[1]['value']+'</td>';
            str += '<td>'+unit_name+'</td>';
            str += '<td>'+$('#add_product_form').serializeArray()[3]['value']+'</td>';
            str += '<td>'+$('#add_product_form').serializeArray()[4]['value']+'</td>';
            str += '<td>'+$('#add_product_form').serializeArray()[5]['value']+'</td>';
            str += '</tr>';
			$.ajax({
				type	: 'POST',
				url		: 'query.php',
				data	: {add_products:true, data:$('form').serializeArray()},
				dataType: 'html',
				beforeSend:function(){ $('.loading').html('<img src="css/images/loading.gif" alt="loading" />'); },
				success	: function(msg){
					$('.products-template .products-input-template').clone(true).appendTo('.products .products-group');
					$('.products .products-group').find('.products-input-template').last().find('input[type=hidden]')
					.val(randomString(10,10));
					$('#add_product_form table tbody').first().prepend(str)
					$('.products .products-group').find('.products-input-template')
					.last().prev().remove();
					$('.loading').html('<img src="css/images/success.png" alt="success" />');
				}
			});
		}
	});

	$('#add_member_btn').click(function(){
	    $(this).closest('form').submit();
	});
    $('#add_customer_btn').click(function(){
	    $(this).closest('form').submit();
	});
    $('#add_saler_btn').click(function(){
	    $(this).closest('form').submit();
	});
	$('#profile_btn').click(function(){
	    var pwd = $(this).closest('form').find('#password').val();
	    var confirm_password = $(this).closest('form').find('#confirm_password').val();
	    if(pwd != ""){
            if(pwd == confirm_password){
                $(this).closest('form').submit();
            }else{
                alert('ยืนยันรหัสผ่านจะต้องตรงกันกับรหัสผ่าน');
            }
	    }else{
	        $(this).closest('form').submit();
	    }
	});
	$('a#delete').click(function(){
	    var table_name = $(this).closest('.products-list').find('#table_name').val();
	    var item_id = $(this).closest('tr').find('#id').val();
	    var tr = $(this).closest('tr');
	    $.ajax({
	        type    : 'POST',
	        url     : 'query.php',
	        data    : {delete:true, table_name:table_name, id:item_id},
	        dataType: 'html',
	        success : function(msg){
	            if(msg == 1){
	                tr.fadeOut('slow');
	            }
	        }
	    });
	    return false;
	});

	$('a#edit_member_btn').click(function(){
	    $(this).closest('form').submit();
	});
    $('a#edit_customer_btn').click(function(){
	    $(this).closest('form').submit();
	});
    $('a#edit_saler_btn').click(function(){
	    $(this).closest('form').submit();
	});
});

